package com.zkane.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author: keluosi@bicitech.cn
 * @date: 2018/4/18
 */
@RestController
public class SessionController {

    @GetMapping("/test/session")
    public String testSession(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String brower = (String) session.getAttribute("brower");
        if (brower == null) {
            System.out.println("session 中不存在brower，设置 brower=" + request.getParameter("brower"));
            session.setAttribute("brower", request.getParameter("brower"));
        } else {
            System.out.println("session 中存在 brower=" + brower);
        }
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                // cookie.setDomain(".yourAddress.com");
                
                System.out.println("cookie: " + cookie.getName() + ": " + cookie.getValue());
            }
        }
        return "success";
    }

    @Autowired
    FindByIndexNameSessionRepository sessionRepository;

    @GetMapping("/test/findByUsername")
    public Map findByUsername(@RequestParam String username) {
        Map<String, Session> usersSessions = sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username);
        return usersSessions;
    }
}


